package com.earogya.logic.patient_details;

import java.util.Calendar;

import org.apache.struts.ehr.medical_records.model.AdmitPatient;
import org.apache.struts.ehr.medical_records.model.Guardian;
import org.apache.struts.ehr.medical_records.model.Address;
import org.apache.struts.ehr.medical_records.model.MergePatientLog;

import com.earogya.Constants;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.v251.datatype.ST;
import ca.uhn.hl7v2.model.v251.message.ADT_A30;

/**
 * 
 * Create a ADT A34 message based on the user input
 * Used to merge two patients
 * 
 * @author Ureka
 *
 */
public class CreateADTA34 {

	private ADT_A30 adt;
	private int newPatientId;
	private int currentPatientId;
	
	
	public CreateADTA34(int newPatientId,int currentPatientId){
		this.adt=new ADT_A30();
		this.newPatientId=newPatientId;
		this.currentPatientId=currentPatientId;
	}
	
	/**
	 * 
	 * Create the message
	 * 
	 * @param sendingFacility
	 * @return
	 * @throws HL7Exception
	 */
	public String createMessage(String sendingFacility) throws HL7Exception{
		this.addMessageHeader(sendingFacility);
		this.addMergeInformation();
		return adt.getMessage().encode();
	}
	
	
	/**
	 * 
	 * Create the message header
	 * 
	 * @param sendingFacility
	 * @throws DataTypeException
	 */
	private void addMessageHeader(String sendingFacility) throws DataTypeException{
		adt.getMSH().getFieldSeparator().setValue("|");
		adt.getMSH().getEncodingCharacters().setValue("^~\\&");
		adt.getMSH().getDateTimeOfMessage().getTime().setValue(Calendar.getInstance().getTime());
		adt.getMSH().getMessageType().getMsg1_MessageCode().setValue("ADT");
		adt.getMSH().getMessageType().getTriggerEvent().setValue("A34");
		adt.getMSH().getSendingApplication().getUniversalID().setValue(Constants.SENDING_APPLICATION);
		adt.getMSH().getVersionID().getVersionID().setValue(Constants.HL7_VERSION);
		adt.getMSH().getSendingFacility().getUniversalID().setValue(sendingFacility);
		adt.getMSH().getReceivingApplication().getUniversalID().setValue(Constants.RECEIVING_APPLICATION_PATIENT_DETAILS_SERVICE);
		adt.getMSH().getReceivingFacility().getUniversalID().setValue(sendingFacility);
	}
	
	/**
	 * 
	 * Merge the demographic details and the medical records
	 * 
	 * @throws DataTypeException
	 */
	private void addMergeInformation() throws DataTypeException{
		adt.getMRG().getPriorPatientID().getIDNumber().setValue(String.valueOf(this.currentPatientId));
		adt.getPID().getPatientID().getIDNumber().setValue(String.valueOf(this.newPatientId));
		}

}
